package com.rabbit.aspect;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.rabbit.exception.BusinessException;
import com.rabbit.redis.annotation.Cacheable;
import com.rabbit.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

/**
 * <h1>缓存切面</h1>
 *
 * @author zjw
 * @date 2021/6/28 9:27
 */
@Aspect
@Component
@Order(3)
@Slf4j
public class CacheAspect {

    @Resource
    private RedisService redisService;

    /**
     * 拦截使用了Cacheable注解的方法
     */
    @Around("@annotation(cacheable)")
    public Object around(ProceedingJoinPoint joinPoint, Cacheable cacheable) throws BusinessException {
        return getObject(joinPoint, cacheable);
    }

    public Object getObject(ProceedingJoinPoint joinPoint, Cacheable cacheable) throws BusinessException {
        Cacheable.CACHE_TYPE cacheType = cacheable.cacheType();
        String redisKey = cacheable.key();
        // 拼接Redis Key
        String suffix = cacheable.keySuffix();
        if (StringUtils.hasText(suffix)) {
            Object[] args = joinPoint.getArgs();
            try {
                if (args.length > 0) {
                    Class<?> argClass = args[0].getClass();
                    String[] suffixArr = suffix.split(";");
                    Field[] fields = argClass.getDeclaredFields();
                    for (String str : suffixArr) {
                        if (str.contains("#")) {
                            str = str.substring(1);
                            for (Field field : fields) {
                                if (str.equals(field.getName())) {
                                    field.setAccessible(true);
                                    Object val = field.get(args[0]);
                                    redisKey += val;
                                    break;
                                }
                            }
                        } else {
                            redisKey += str;
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        Object object;
        if (cacheType == Cacheable.CACHE_TYPE.UPDATE) {
            object = updateObject(joinPoint, redisKey);
        } else {
            object = findObject(joinPoint, cacheable, redisKey);
        }
        return object;
    }

    private Object findObject(ProceedingJoinPoint joinPoint, Cacheable cacheable, String key) {
        Class<?> targetClass = cacheable.targetClass();
        TimeUnit timeUnit = cacheable.timeUnit();
        int expire = cacheable.expire();
        Cacheable.EXPIRE_TYPE expireType = cacheable.expireType();
        // 检查缓存中是否有数据
        String result = redisService.get(key);
        Object object;
        try {
            if (StringUtils.hasLength(result)) {
                log.info("缓存存在，查询缓存，Key:{}", key);
                if (result.length() > 0) {
                    if (result.charAt(0) == '[') {
                        object = JSON.parseArray(result, targetClass);
                    } else {
                        object = JSON.parseObject(result, targetClass);
                    }
                } else {
                    object = JSON.parseObject(result, targetClass);
                }
            } else {
                log.info("缓存不存在，查询数据库，Key:{}", key);
                // 缓存中没有数据,查询数据库
                object = joinPoint.proceed();
                String json = JSON.toJSONString(object);
                // 判断过期策略
                if (expireType != Cacheable.EXPIRE_TYPE.NEVER) {
                    if (expireType == Cacheable.EXPIRE_TYPE.RANDOM) {
                        expire = RandomUtil.randomInt(24, 48);
                        timeUnit = TimeUnit.HOURS;
                    }
                    redisService.setEx(key, json, expire, timeUnit);
                } else {
                    redisService.set(key, json);
                }
            }
        } catch (Throwable e) {
            log.error("查询缓存遇到错误，Key:{},错误原因：", key, e);
            throw new RuntimeException("查询缓存失败,Key:" + key);
        }
        return object;
    }

    private Object updateObject(ProceedingJoinPoint joinPoint, String key) throws BusinessException {
        Object object;
        try {
            object = joinPoint.proceed();
            redisService.delete(key);
            log.info("删除缓存，Key:{}", key);
        } catch (BusinessException e) {
            throw e;
        } catch (Throwable e) {
            log.error("删除缓存遇到错误，Key:{},错误原因：", key, e);
            throw new RuntimeException("删除缓存失败,Key:" + key);
        }
        return object;
    }
}
